package com.senran.robot.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.senran.robot.service.AutomaticReplyService;
import com.senran.robot.utils.ParamsUtil;
import com.senran.robot.utils.WebSocketClient;
import org.apache.commons.lang.StringUtils;
import org.java_websocket.enums.ReadyState;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

@Service
public class AutomaticReplyServiceImpl implements AutomaticReplyService {

    public static WebDriver webDriver;
    private static volatile boolean coon = false;
    private static volatile boolean close = false;

    private static volatile Set<String> set = new LinkedHashSet<>();

    private static  Set<String> nextSet = new LinkedHashSet<>();
    private  Set<String> errorSet = new LinkedHashSet<>();
    @Override
    public void getRoomSend(Integer roomId) {
        int ExecuteSecond = 6000; //监听时间秒
        String appId = "q7777b133e101fee";      //小程序开发者ID（成为开发者后，https://ext.huya.com可查）
        String secret = "ae2425c3d154ffe3001c20da6cdd6024";     //小程序开发者密钥（成为开发者后，https://ext.huya.com可查）

        System.setProperty("webdriver.chrome.driver", "F:\\laji\\chromedriver_win32\\chromedriver.exe");
        System.setProperty("webdriver.chrome.bin", "C:\\Users\\Administrator\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
        ChromeOptions chromeOptions = new ChromeOptions();
//        chromeOptions.addArguments("--headless");//不打开浏览器UI显示
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--start-maximized");
        webDriver = new ChromeDriver(chromeOptions);
        Thread connectRoom = new Thread(() -> {
//        long roomId = 11334154;        //监听主播的房间号11334154 15276487  11352944
            webDriver.get("https://www.huya.com/"+roomId);
            login();
        });
        webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        sendBulletChat();
        connectRoom.start();
        System.out.println(webDriver.getTitle());
        try {
            Map<String, Object> map = new HashMap<String, Object>(16);
            map = WebSocketClient.getWebSocketJwtParamsMap(appId,secret,roomId);
            System.out.println(map);
            StringBuffer urlBuffer = new StringBuffer();
            urlBuffer.append("ws://ws-apiext.huya.com/index.html").append(ParamsUtil.MapToUrlString(map));

            WebSocketClient client = new WebSocketClient(URI.create(urlBuffer.toString()));
            client.setConnectionLostTimeout(3600);
            client.connect();
            while (!client.getReadyState().equals(ReadyState.OPEN)) {
            }
            Long reqId = System.currentTimeMillis();
            String sendMsg = "{\"command\":\"subscribeNotice\",\"data\":[\"getSendItemNotice\",\"getVipEnterBannerNotice\",\"getMessageNotice\"],\"reqId\":\"" + reqId + "\"}";
            client.send(sendMsg);
            int count = 1;
            while (count < ExecuteSecond) {
                Thread.sleep(1000);
//                System.out.println("connect time:" + count);
                client.send("ping");
                count++;
            }
            client.closeConnection(0,"bye");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 欢迎用户进入
     * @param res
     */
    public static void sendHuanYing(JSONObject res){
//            System.out.println("-------- 进场人:"+WebSocketClient.convertUnicodeToCh(res.getJSONObject("data").getString("userNick")) );
//            System.out.println("-------- 徽章名称:"+WebSocketClient.convertUnicodeToCh(res.getJSONObject("data").getString("nobleName")) );
//            System.out.println("-------- 用户等级:"+res.getJSONObject("data").getInteger("userLevel") );
        String name = WebSocketClient.convertUnicodeToCh(res.getJSONObject("data").getString("userNick"));
        nextSet.add(name);
        if(nextSet.size()>5 && !close){
            System.out.println("--------------set:"+nextSet.toString());
            set.addAll(nextSet);
            nextSet.clear();
            close = true;
        }
    }

    private void login(){
//        Thread.sleep(3000);
//        webDriver.manage().window().maximize();//窗口最大
        webDriver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
        try {
            webDriver.findElement(By.xpath("//*[@id=\"player-brower-pause-guide\"]/div[2]/div[2]")).click();
            webDriver.findElement(By.xpath("//*[@id=\"J_duyaHeaderRight\"]/div/div[2]")).click();
            webDriver.switchTo().frame("UDBSdkLgn_iframe");
            webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
            webDriver.findElement(By.xpath("//*[@id=\"quick-login-section\"]/div[4]")).click();
            webDriver.findElement(By.xpath("//*[@id=\"account-login-form\"]/div[1]/input")).sendKeys("14779861745");
            webDriver.findElement(By.xpath("//*[@id=\"account-login-form\"]/div[2]/input")).sendKeys("zhu14779861745.");
            webDriver.findElement(By.xpath("//*[@id=\"login-btn\"]")).click();
            coon = true;
        }catch (Exception e){
            System.out.println("不是显示扫码登录");
            login();
        }
    }

    private void sendBulletChat(){
        AtomicBoolean isContinue = new AtomicBoolean(true);
        Thread thread = new Thread(()->{
            int i = 0;
            while (isContinue.get()) {
                try {
                    if (coon && set.size() > 5 && close) {
                        System.out.println("发送弹幕!!!!!!!!!");
                        Iterator<String> it = set.iterator();
                        while (it.hasNext()) {
                            Thread.sleep(1000);
                            String str = it.next();
//                            System.out.println("--------------进场人:"+str);
                            webDriver.findElement(By.xpath("//*[@id=\"pub_msg_input\"]")).sendKeys(
                                    "欢迎" + str + ",热烈欢迎/{hx/{hx/{hx");
                            webDriver.findElement(By.xpath("//*[@id=\"msg_send_bt\"]")).click();
                            if(StringUtils.isNotBlank(webDriver.findElement(By.xpath("//*[@id=\"pub_msg_input\"]")).getText())){
                                webDriver.findElement(By.xpath("//*[@id=\"pub_msg_input\"]")).clear();
                                errorSet.add(str);
                                i++;
                            }
                            it.remove();
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    sendBulletChat();
                    isContinue.set(false);
                }finally {
                    close = false;
                    if(errorSet.size()>0&&i >= 10){
                        i = 0;
                        System.out.println("发送失败的有："+errorSet.toString());
                    }
                }
            }
        });
        thread.start();
    }
}
